#include "enemy1.h"
#include "waypoint.h"
#include "towerbase1.h"
#include "utility.h"
#include "window3.h"

#include <QPainter>
#include <QColor>
#include <QDebug>
#include <QMatrix>
#include <QVector2D>
#include <QtMath>

static const int Health_Bar_Width = 20;

const QSize Enemy1::ms_fixedSize(52, 52);

Enemy1::Enemy1(waypoint *start, window3 *game1, const QPixmap &pic/* = QPixmap(":/fls.png")*/)
    : QObject(0)
    , can_move(false)
    , _Hp(200)
    , _currentHp(40)
    , _speed(1.0)
    , _rotation(0.0)
    , _pos(start->pos())
    , _destination_point(start->next_waypoint())
    , _game1(game1)
    , _pic(pic)
{
}

Enemy1::~Enemy1()
{

    _destination_point = NULL;
    _game1 = NULL;
}

void Enemy1::doActivate()
{
    can_move = true;
}

void Enemy1::move()
{
    if (!can_move)
        return;

    if (if_collision(_pos, 1, _destination_point->pos(), 1))
    {

        if (_destination_point->next_waypoint())
        {

            _pos = _destination_point->pos();
            _destination_point = _destination_point->next_waypoint();
        }
        else
        {

            _game1->Hp_damage(1);
            _game1->remove_enemy(this);
            return;
        }
    }


    QPoint targetPoint = _destination_point->pos();

    qreal move_Speed = _speed;
    QVector2D normalized(targetPoint - _pos);
    normalized.normalize();
    _pos = _pos + normalized.toPoint() * move_Speed;


    _rotation = qRadiansToDegrees(qAtan2(normalized.y(), normalized.x())) + 180;
}

void Enemy1::draw(QPainter *painter) const
{
    if (!can_move)
        return;

    painter->save();

    QPoint healthBarPoint = _pos + QPoint(-Health_Bar_Width / 2 - 1, -ms_fixedSize.height() / 2-3);

    painter->setPen(Qt::NoPen);
    painter->setBrush(Qt::red);
    QRect healthBarBackRect(healthBarPoint, QSize(Health_Bar_Width, 2));
    painter->drawRect(healthBarBackRect);

    painter->setBrush(Qt::green);
    QRect healthBarRect(healthBarPoint, QSize((double)_currentHp / _Hp * Health_Bar_Width, 2));
    painter->drawRect(healthBarRect);


    static const QPoint offsetPoint(-ms_fixedSize.width() / 2, -ms_fixedSize.height() / 2);
    painter->translate(_pos);
    painter->rotate(_rotation);

    painter->drawPixmap(offsetPoint, _pic);

    painter->restore();
}



QPoint Enemy1::pos() const
{
    return _pos;
}


void Enemy1::get_attacked(towerbase1 *attacker){
    m_attackedTowersList.push_back(attacker);
}
void Enemy1::get_lostsight(towerbase1 *attacker){
    m_attackedTowersList.removeOne(attacker);
}

void Enemy1::get_damage(int damage)
{
    _Hp -= damage;

    if (_Hp <= 0)
    {
        _game1->awardgold(200);
        getRemoved();
    }
}
void Enemy1::getRemoved(){
    foreach (towerbase1 *attacker, m_attackedTowersList)
        attacker->target_killed();

    _game1->remove_enemy(this);
}
